<template>
  <div class="content">
    <el-upload
      action
      :http-request="upload"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :drag="listType!=='picture'"
      :accept="accept"
      :limit="limit"
      :file-list="fileList"
      :list-type="listType"
    >

      <el-button v-if="listType==='picture'" size="small" type="primary">点击上传</el-button>

      <i v-if="listType!=='picture'" class="el-icon-upload" />
      <div v-if="listType!=='picture'" class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div v-if="tips" slot="tip" class="el-upload__tip">{{ tips }}</div>
    </el-upload>

    <el-progress
      v-show="showProgress"
      :text-inside="true"
      :stroke-width="15"
      :percentage="progress"
    />
  </div>
</template>

<script>
import axios from 'axios'
import { buildDir } from '@/utils/file-utils'
import { fetchToken } from '@/api/sys/config/oss'

export default {
  name: 'FileUploadOss',
  props: {
    value: String,
    accept: String,
    tips: String,
    listType: String,
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [], // 文件列
      showProgress: false, // 进度条的显示
      dataObj: {}, // 存签名信息
      progress: 0 // 进度条数据
    }
  },
  watch: {
    // 检测查询变化
    value: {
      handler() {
        this.fillValue()
      }
    }
  },

  created() {
    this.fillValue()
  },
  methods: {

    // 填充数据
    fillValue() {
      this.fileList = []
      this.fileUrl = this.value
      if (this.fileUrl) {
        this.fileList = [{ name: this.fileUrl, url: this.fileUrl }]
      }
    },

    // 文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning(`每次只能上传 ${this.limit} 个文件`)
    },
    // 删除文件之前的钩子
    beforeRemove() {
      return this.$confirm(`确定移除文件吗？`)
    },
    // 文件列表移除文件时的钩子
    handleRemove() {
      this.$emit('input', '')
      this.fileList = []
    },
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      this.fileList = fileList
    },

    // 自定义上传实现
    upload(file) {
      fetchToken().then(res => {
        this.uploadWithToken(file, res.data)
      }).catch(err => {
        console.log(err)
      })
    },

    // 上传进度监听
    onProgress(e) {
      this.showProgress = true
      this.progress = (e.loaded / e.total * 100 | 0)
    },

    // 重命名文件
    buildName(file) {
      const temporary = file.file.name.lastIndexOf('.')
      const fileNameLength = file.file.name.length
      const fileFormat = file.file.name.substring(
        temporary + 1,
        fileNameLength
      )
      return buildDir() + '.' + fileFormat
    },

    // 上传用token
    uploadWithToken(file, data) {
      console.log(data)

      const fileName = this.buildName(file)
      const formData = new FormData()

      formData.append('key', fileName)
      formData.append('policy', data.policy)
      formData.append('OSSAccessKeyId', data.accessid)
      formData.append('success_action_status', 200)
      formData.append('signature', data.signature)
      formData.append('file', file.file, file.file.name)

      axios.post(data.host, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: this.onProgress
      }).then(res => {
        if (res.status == 200) {
          // 上传成功回调
          console.log(res)
          this.showProgress = false
          this.$emit('input', data.url + fileName)
        }
      }).catch(err => {
        console.log('err:', err)
      })
    }
  }
}
</script>
